package com.movisol.seduceme.receivers;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;

import com.movisol.c2dm.R;
import com.movisol.c2dm.receivers.C2DMBaseReceiver;

public class C2DMReceiver extends C2DMBaseReceiver {
	private String msg = null;

	
    public C2DMReceiver() {  
        // Email address currently not used by the C2DM Messaging framework  
        super("android@movisol.com");  //Sustituir por 689648192915 para usar la nueva API GCM
    }  
  
    @Override  
    public void onRegistered(Context context, String registrationId) {  
        Log.d("C2DM", "Registration ID arrived: Fantastic!!!");  
        Log.d("C2DM", registrationId);
		fireRegistrationIdReceived(registrationId);
    }  
  
    @Override  
    protected void onMessage(Context context, Intent intent) {  
        Log.d("C2DM", "Message: Fantastic!!!");
        
        String type = null;
        if(intent.getExtras() != null)
        {
        	type = intent.getStringExtra("type");
        }
        
        if(type != null)
        {
        	if(type.equals("c-update"))
        	{
        		msg = intent.getStringExtra("url");
        		createNewMessageNotification(context, type);
        	}
        }
    }  
  
    @Override  
    public void onError(Context context, String errorId) {  
        Log.d("C2DM", "Error occured!!!");
        fireRegistrationIdReceived(null);
    }  
  
	public void createNewMessageNotification(Context context, String type) {
		NotificationManager notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = new Notification(R.drawable.ic_notification, "Actualizacion de Seduceme", System.currentTimeMillis());
		// Hide the notification after its selected
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		notification.defaults |= Notification.DEFAULT_VIBRATE;
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setData(Uri.parse(msg));
				
		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
		notification.setLatestEventInfo(context, "Actualizacion de Seduceme", "Pincha para descargar la nueva version", pendingIntent);		
		notificationManager.notify(0, notification);

	}

}  